/**
 * 
 */

package com.kugou.game.sdk.ui.fragment;

import com.kugou.framework.utils.NetWorkUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 描述:绑定安全邮箱
 *
 * @author jerryliu
 * @since 2015年8月19日 下午3:04:30
 */
public class SecurityEmailBindFragment extends BaseSDKWorkerFragment implements OnClickListener {

    private static final int MSG_BACK_REQUEST_VALIDATE_CODE = 1;

    private static final int MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS = 2;

    private static final int MSG_UI_REQUEST_VALIDATE_CODE_FAILE = 3;

    private static final int MSG_UI_START_COUNT_DOWN = 4;

    private static final int MSG_BACK_BIND_SECURITY_EMAIL = 5;

    private static final int MSG_UI_BIND_SECURITY_EMAIL_SUCCESS = 6;

    private static final int MSG_UI_BIND_SECURITY_EMAIL_FAILE = 7;

    private Activity context;

    private TextView tvAccount, tvGetAuthCode, tvAuthCodeState;

    private EditText etLoginPsd, etBindEmail, etAuthCode;

    private Button btnConfirm;

    private LoadingView loadingView;

    private View layoutBindEmail;

    private int countDownMinute = 60;

    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(Rx.layout.kg_fragment_security_email_bind, null);
        initView(view);
        setListener();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    private void initView(View view) {
        loadingView = (LoadingView) view.findViewById(Rx.id.kg_loadingView);
        loadingView.setText("正在操作，请稍候…");
        layoutBindEmail = view.findViewById(Rx.id.kg_layout_bind_phone);
        tvAccount = (TextView) view.findViewById(Rx.id.kg_tv_username);
        tvAccount.setText(user.getAccountName());
        tvAuthCodeState = (TextView) view.findViewById(Rx.id.kg_tv_auth_code_state);
        etBindEmail = (EditText) view.findViewById(Rx.id.kg_et_phone_number);
        etAuthCode = (EditText) view.findViewById(Rx.id.kg_et_auth_code);
        etLoginPsd = (EditText) view.findViewById(Rx.id.kg_et_psd);
        tvGetAuthCode = (TextView) view.findViewById(Rx.id.kg_tv_get_auth_code);
        btnConfirm = (Button) view.findViewById(Rx.id.kg_btn_confirm);
    }

    private void setListener() {
        tvGetAuthCode.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        hideSoftInput(context);
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            showToast("请检查您的网络连接");
            return;
        }

        String email = etBindEmail.getText().toString().trim();
        if (v == tvGetAuthCode) {
            if (!AppUtil.isEmailCorrect(email)) {
                showToast("请填写正确绑定邮箱");
                return;
            }

            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_VALIDATE_CODE);
        } else if (v == btnConfirm) {
            String loginPsd = etLoginPsd.getText().toString().trim();
            String code = etAuthCode.getText().toString().trim();
            if (TextUtils.isEmpty(loginPsd)) {
                showToast("请输入登录密码");
                return;
            }

            // if (!loginPsd.equals(user.getPassword())) {
            // showToast("您输入的登录密码不正确");
            // return;
            // }

            if (!AppUtil.isEmailCorrect(email)) {
                showToast("请填写正确的绑定邮箱");
                return;
            }

            if (TextUtils.isEmpty(code)) {
                showToast("请输入邮箱中收到的验证码");
                return;
            }

            loadingView.setVisibility(View.VISIBLE);
            layoutBindEmail.setVisibility(View.GONE);
            sendEmptyBackgroundMessage(MSG_BACK_BIND_SECURITY_EMAIL);
        }

    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        final Message message = new Message();
        String username = user.getAccountName();
        String kgToken = user.getKugouToken();
        String checkcode = etAuthCode.getText().toString().trim();
        String securityEmail = etBindEmail.getText().toString().trim();
        String password = etLoginPsd.getText().toString().trim();
        switch (msg.what) {
            case MSG_BACK_REQUEST_VALIDATE_CODE:
                sendEmptyUiMessage(MSG_UI_START_COUNT_DOWN);
                UserManager.getInstance().sendSecurityEmailCode(username, kgToken, securityEmail,
                        1, new OnRequestListener() {
                            @Override
                            public void onSuccess() {
                                message.what = MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_UI_REQUEST_VALIDATE_CODE_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                break;
            case MSG_BACK_BIND_SECURITY_EMAIL:
                UserManager.getInstance().setSecurityEmail(username, securityEmail, checkcode,
                        password, new onAccountSecurityInfoListener() {
                            @Override
                            public void onSuccess(AccountSecurityInfo info) {
                                message.what = MSG_UI_BIND_SECURITY_EMAIL_SUCCESS;
                                message.obj = info;
                            }

                            @Override
                            public void onFaile(String errorMsg) {
                                message.what = MSG_UI_BIND_SECURITY_EMAIL_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                break;
        }
        sendUiMessage(message);
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        switch (msg.what) {
            case MSG_UI_START_COUNT_DOWN:
                if (countDownMinute > 0) {
                    tvGetAuthCode.setText(countDownMinute + "秒");
                    tvGetAuthCode.setEnabled(false);
                    countDownMinute--;
                    sendEmptyUiMessageDelayed(MSG_UI_START_COUNT_DOWN, 1000);
                } else {
                    tvGetAuthCode.setText("获取验证码");
                    tvGetAuthCode.setEnabled(true);
                    countDownMinute = 60;
                }
                break;
            case MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS:
                showToast("验证码成功发送到邮箱，请注意查收");
                tvAuthCodeState.setVisibility(View.VISIBLE);
                tvAuthCodeState.setText(Html.fromHtml("已发送验证码到邮箱<font color =\"#249EF6\" >"
                        + AppUtil.getEmailWithStar(etBindEmail.getText().toString().trim())
                        + "</font>"));
                break;
            case MSG_UI_REQUEST_VALIDATE_CODE_FAILE:
                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }

                removeUiMessage(MSG_UI_START_COUNT_DOWN);
                tvGetAuthCode.setText("获取验证码");
                tvGetAuthCode.setEnabled(true);
                countDownMinute = 60;
                break;
            case MSG_UI_BIND_SECURITY_EMAIL_SUCCESS:
                loadingView.setVisibility(View.GONE);
                layoutBindEmail.setVisibility(View.VISIBLE);
                context.sendBroadcast(new Intent(
                        SDKActions.ACTION_UPDATE_BIND_SECURITY_EMAIL_SUCCESS));

                final BaseConfirmDialog dialog = new BaseConfirmDialog(context);
                dialog.setMessage(Html.fromHtml("绑定成功，您的安全邮箱为\n<font color =\"#249EF6\" >"
                        + user.getSecurityEmail() + "</font>"));
                dialog.setSuccessLogoVisibility(View.VISIBLE);
                dialog.setDialogTitle("提示");
                dialog.setCancelBtnVisibility(View.GONE);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOKBtnText("知道了");
                dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
                dialog.setCancelable(false);
                dialog.setOKClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        dialog.dismiss();

                        if (getActivity() != null && !getActivity().isFinishing()) {
                            getActivity().finish();
                        }
                    }

                });
                dialog.show();
                break;
            case MSG_UI_BIND_SECURITY_EMAIL_FAILE:
                loadingView.setVisibility(View.GONE);
                layoutBindEmail.setVisibility(View.VISIBLE);
                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }
                break;
        }
    }
}
